package Tools;

import java.io.*;

/**
 * 类功能描述：
 *用于对容器进行序列化和反序列化存储
 * @author lix
 * @date 2023/12/30
 */

public class Serializer {

    private String folderPath =".\\SerializedContainer";

    /**
     * 功能描述：
     *序列化方法
     * @param container 序列化对象
     * @param filename 文件路径
     * @author lix
     * @date 2023/12/30
     */

    public void serializeFigures(FiguresContainer container, String filename){
        try {
            // 创建目录
            File folder = new File(folderPath);
            if (!folder.exists()) {
                folder.mkdirs();  // 创建多层目录
            }
            // 组合完整的文件路径
            String fullPath = folderPath + "\\" + filename;

            // 打开文件输出流
            FileOutputStream fileOut = new FileOutputStream(fullPath);

            // 打开对象输出流
            ObjectOutputStream objectOut = new ObjectOutputStream(fileOut);

            // 序列化对象
            objectOut.writeObject(container);

            // 关闭流
            objectOut.close();
            fileOut.close();

            System.out.println("Serialization completed. File saved at: " + fullPath);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    public  Object deserializeFigures(String filename) {
        Object obj = null;
        try {
            // 指定目标文件路径


            // 组合完整的文件路径
            String fullPath = folderPath + "\\" + filename;

            // 打开文件输入流
            FileInputStream fileIn = new FileInputStream(fullPath);

            // 打开对象输入流
            ObjectInputStream objectIn = new ObjectInputStream(fileIn);

            // 反序列化对象
            obj = objectIn.readObject();

            // 关闭流
            objectIn.close();
            fileIn.close();

            System.out.println("Deserialization completed. Object loaded from: " + fullPath);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return obj;
    }



}
